<?php
namespace app\index\controller;

use app\index\controller\Base;
use app\common\model\Article as ArticleModel;
use app\common\model\Category as CategoryModel;

class News extends Base
{
    public function initialize()
    {
        parent::initialize();
        $this->Model = new ArticleModel();
        $first_category_name = 'news';
        $this->CategoryModel = new CategoryModel();
        $category_tree = $this->CategoryModel->treeView(true);
        if(isset($category_tree[$first_category_name])){
          $tree_node = $category_tree[$first_category_name];
        }else{
          $tree_node = $this->CategoryModel->emptyTreeRootNode();
        }
        $this->tree_node = $tree_node;
        $this->assign('active_nav', $first_category_name);
    }

    public function index()
    {
        $param = [];
        $param = $this->request->param();
        $default_param = $this->index_default_param();

        $cat_id = 0;
        if(isset($this->tree_node['children'])){
            $categories = $this->tree_node['children'];
            if(isset($param['cat_id']) && isset($categories[$param['cat_id']])){
                $cat_id = $param['cat_id'];
            }else{
                if(isset($this->tree_node['default_second_category_id'])){
                    $cat_id = $this->tree_node['default_second_category_id'];
                }
            }
        }
        $default_param['cat_id'] = $cat_id;

        $hot_item = $this->Model->hotItem($cat_id, $this->tree_node['id']);
        if(!empty($hot_item)){
            $default_param['except_id'] = $hot_item['id'];
        }

        $res = $this->Model->userPaginate(array_merge($param, $default_param));
        $this->assign("tree_node", $this->tree_node);
        $this->assign("cat_id", $cat_id);
        $this->assign("hot_item", $hot_item);
        $this->assign("res", $res);

        // 设置页面SEO信息
        $this->setPageSeo([
            'title' => $this->tree_node['title'],
            'description' => $this->tree_node['seo_description'],
            'keywords' => $this->tree_node['seo_keywords'],
        ]);

        return $this->fetch();
    }

    public function read($id = 0)
    {
        $article = $this->findValidArticle($id);
        if(empty($article)){
            $this->redirect('index');
        }
        $this->assign('article', $article);

        // 设置页面SEO信息
        $this->setPageSeo([
            'title' => $article['title'],
            'description' => $article['seo_description'],
            'keywords' => $article['seo_keywords'],
        ]);

        return $this->fetch();
    }

    // public function demo(){
    //     // $res = $this->Model->hotItem(3, 1);
    //     $res = $this->Model->showCacheValue('view_list');
    //     return json($res);
    // }
}
